package com.slife.snap.service;

import com.fazecast.jSerialComm.SerialPort;
import com.fazecast.jSerialComm.SerialPortDataListener;
import com.fazecast.jSerialComm.SerialPortEvent;
import com.slife.snap.domain.PdSerialportinfo;
import com.slife.snap.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


@Service
@Slf4j
public class SerialListenerService {
//串口设备描述
    private static final String VIRTUAL_SERIAL = "slife";

    public final static Logger logger = LoggerFactory.getLogger(SerialListenerService.class);
    @Autowired
    private PdSerialportinfoService serialportinfoService;
    private static final int SAFETY_SLEEP_TIME = 660;
//    private static final int SAFETY_SLEEP_TIME = 2000;

    private static final int DEFAULT_BAUD_RATE = 1200;
//    private static final int DEFAULT_BAUD_RATE = 9600;

    private static final int DEFAULT_DATA_BITS = 8;


    /**
     * 查询当前设备的端口名称
     */
    public List<String> getPortNames(){
        SerialPort[] ports = SerialPort.getCommPorts();
        List<String> portNames = new ArrayList<>();
        for (SerialPort port : ports) {
            if (port.getPortDescription().contains(VIRTUAL_SERIAL)){
                portNames.add(port.getSystemPortName());
            }
        }
        return portNames;
    }

    public Double interToDouble(String number) {
        BigDecimal bd = BigDecimal.valueOf(Double.parseDouble(number) / 1000);
        return bd.setScale(2, RoundingMode.HALF_DOWN ).doubleValue();


    }

    /**
     * 打开串口
     */
    public SerialPort openDevice(String portName){
        SerialPort commPort = SerialPort.getCommPort(portName);
        if (commPort.isOpen()){
            return commPort;
        }
        if (commPort.openPort()){
            //打开串口成功，设置端口参数
            commPort.setBaudRate(DEFAULT_BAUD_RATE);
            commPort.setComPortTimeouts(SerialPort.TIMEOUT_NONBLOCKING, 0, 0);
            //设置监听器
            commPort.addDataListener(new SerialPortDataListener() {
                @Override
                public int getListeningEvents() {
                    return SerialPort.LISTENING_EVENT_DATA_AVAILABLE;
                }

                @Override
                public void serialEvent(SerialPortEvent serialPortEvent) {
                    if (serialPortEvent.getEventType() != SerialPort.LISTENING_EVENT_DATA_AVAILABLE){
                        return;
                    }
                    byte[] newData = new byte[commPort.bytesAvailable()];
                    int numRead = commPort.readBytes(newData, newData.length);
                    try {
                        try {
                            Thread.sleep(SAFETY_SLEEP_TIME);
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }

                        String message = new String(newData);
                        System.out.println(message);

                        logger.info("message = " + message);
//                        Pattern pattern = Pattern.compile("\\d+");
//                        Matcher matcher = pattern.matcher(message);
//
//                        while (matcher.find()) {
//                            String number = matcher.group();
//                            if (number.length()== 8) {
//                                PdSerialportinfo item = new PdSerialportinfo();
////                              读取地磅值的时候，只取前6位。
//                                item.setWeight(interToDouble(number.substring(0,6)));
//                                item.setMetertime(DateUtils.getNowDate());
//                                serialportinfoService.save(item);
//                            }
//                        }


                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }

                }
            });
            return commPort;
        }
        return null;
    }

    /**
     * 串口发送信息
     */
    public boolean sendMessage(SerialPort serialPort, String msg){
        byte[] msgBytes = msg.getBytes(StandardCharsets.UTF_8);

        return serialPort.writeBytes(msgBytes, msgBytes.length) != -1;
    }
}
